package com.adjaisd.mqtt.controller;

import com.adjaisd.mqtt.common.config.MyMessage;
import com.adjaisd.mqtt.common.result.Result;
import com.adjaisd.mqtt.common.utils.jwt.JwtUtils;
import com.adjaisd.mqtt.entity.Device;
import com.adjaisd.mqtt.entity.User;
import com.adjaisd.mqtt.service.DeviceService;
import com.adjaisd.mqtt.service.RedisService;
import com.adjaisd.mqtt.service.UserService;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
@RequestMapping("/mqtt")
public class MqttController {

    @Autowired
    RedisService redisService;

    @Autowired
    UserService userService;

    @Autowired
    DeviceService deviceService;

    // mqtt身份验证： post: /mqtt/auth
    @RequestMapping(value = "/auth", method = RequestMethod.POST)
    @ResponseBody
    public Result auth(HttpServletResponse response,
                       @RequestBody Map<String, String> map) {
        System.out.println("mqttAuth = " + map);
        String username = map.get("username");
        String password = map.get("password");  // 使用jwt-token验证
        if (username.equals("raspberry") && password.equals("123456")) {
            System.out.println(map);
            response.setStatus(200);
            return Result.succ().code(200).message("验证成功");
        } else if (JwtUtils.checkToken(password)) {
            Claims claims = JwtUtils.getMembers(password);
            System.out.println("claims = " + claims);
            assert claims != null;
            String uname = claims.get("username").toString();
            if (!uname.equals(username)) {
                return Result.fail().code(400).message("用户名验证不通过");
            }
            long id = Long.parseLong(claims.get("id").toString());
            String dKey = "device" + id, uKey = "token" + id;
            if (redisService.existKey(dKey)) { // token是否存在
                Device device = deviceService.getById(id);
                System.out.println("device-suc = " + device + "\t" + map);
                response.setStatus(200);
                return Result.succ().code(200).message("验证成功");
            }
            if (redisService.existKey(uKey)) {
                User user = userService.getUserById(id);
                System.out.println("user-suc = " + user + "\t" + map);
                response.setStatus(200);
                return Result.succ().code(200).message("验证成功");
            }
        }
        response.setStatus(400);
        return Result.fail().code(400).message("验证不通过");
    }

    @Autowired
    MyMessage message;

    @RequestMapping(value = "/msg", method = RequestMethod.GET)
    @ResponseBody
    public Result message() {
        return Result.succ().message(message.getMsg());
    }
}
